<?php 
namespace app\admin\controller;
use app\admin\model\Admin;
use app\admin\model\AdminLogs;
class Login extends \think\Controller{
    public function index(){
        $data = [];
        return view('login/index',$data);
    }
    public function check(){
        $request = \think\Request::instance();
        $lgnTel = $request->post('lgnTel');
        $lgnPsd = $request->post('lgnPsd');
        //调用验证器做验证
        $data = [
            'lgnTel'  => $lgnTel,
            'lgnPsd' => $lgnPsd,
        ];        
        $validate = new \think\Validate([
            'lgnTel|电话号码'  => 'require|\d+',
            'lgnPsd|密码' => 'require'
        ]);
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        //检查数据库中是否有数据
        $admin = new Admin();
        $admindata = $admin->where('phone',$lgnTel)->find();
        if(!$admindata){
            return $this->error('请输入正确的管理员账号！');
        }
        //实例化管理员登录日志的类
        $admin_logs = new AdminLogs();
        //将管理员的id记录到管理员登录日志表中去
        $admin_logs->admin_id = $admindata->id;
        //将管理员的电话号码记录到管理员登录日志表中去
        $admin_logs->phone = $admindata->phone;
        //验证密码的有效性
        $is = password_verify($lgnPsd,$admindata->password);
        if($is){
            //将管理员的id写入到session中
            \think\Session::set('admin_id',$admindata->id);
            //登录成功状态为1
            $admin_logs->state = 1;
            $admin_logs->allowField(true)->save();
            return $this->success('登录成功！','admin/Home/index');
        }else{
            //登录失败状态为0
            $admin_logs->state = 0;
            $admin_logs->allowField(true)->save();
            return $this->error('密码错误，请核对后登录！');
        }
    }
}